<script lang="ts" setup>
import { useUserStore } from "@/stores/user.js";
import UserNoLoginHeader from "@/components/user/UserNoLoginHeader.vue";
import UserHeader from "@/components/user/UserHeader.vue";
import UserNoLoginAside from "@/components/user/UserNoLoginAside.vue";
import UserAside from "@/components/user/UserAside.vue";
import MainPage from "@/components/MainPage.vue";
import instance from "@/utils/request.js";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import router from "@/router/router.js";
import { reactive, ref } from "vue";
import Password from "@/components/Password.vue";
import Inputter from "@/components/Inputter.vue";
import Selector from "@/components/Selector.vue";

// 用户界面的布局容器

// 关闭页面清除登录信息
onMounted(() => {
  window.addEventListener("beforeunload", () => beforeunloadHandler());
  window.addEventListener("unload", () => unloadHandler());
})

// 暴露方法
provide("exit", exit);
provide("login", () => { loginDialogVisible.value = true });
provide("message", () => { messageDialogVisible.value = true });

const user = useUserStore();

let beforeUnload_time = ref();
let gap_time = ref();

const loginDialogVisible = ref(false);
const registerDialogVisible = ref(false);
const messageDialogVisible = ref(false);

// 性别下拉框（表单）
const customer_sex_form_options = [
  { value: '男', label: '男' },
  { value: '女', label: '女' }
];

interface LoginRuleForm {
  user_name: string
  user_password: string
}

interface RegisterRuleForm {
  user_name: string
  user_password: string
  user_password_again: string
}

interface MessageRuleForm {
  customer_name: string
  customer_sex: string
  customer_id: string
  customer_phone: string
}

const ruleFormRef = ref<FormInstance>();

const loginRuleForm = reactive<LoginRuleForm>({
  user_name: '',
  user_password: '',
});

const registerRuleForm = reactive<RegisterRuleForm>({
  user_name: '',
  user_password: '',
  user_password_again: ''
});

const messageRuleForm = reactive<MessageRuleForm>({
  customer_name: '',
  customer_sex: '',
  customer_id: '',
  customer_phone: ''
});

// 确认密码验证
const password1 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空！'));
  }
  else {
    if (registerRuleForm.user_password_again !== '') {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField('user_password_again');
    }
    callback();
  }
}
const password2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('两次密码不一致！'));
  }
  else if (value !== registerRuleForm.user_password) {
    callback(new Error('两次密码不一致！'));
  }
  else {
    callback();
  }
}

const loginRules = reactive<FormRules<LoginRuleForm>>({
  user_name: [
    { required: true, message: '账号名不能为空！', trigger: 'blur' }
  ],
  user_password: [
    { required: true, message: '密码不能为空！', trigger: 'blur' },
  ],
});

const registerRules = reactive<FormRules<RegisterRuleForm>>({
  user_name: [
    { required: true, message: '账号名不能为空！', trigger: 'blur' },
    { min: 1, max: 8, message: '1-8个字符', trigger: 'blur'}
  ],
  user_password: [
    { required: true, message: '密码不能为空！', trigger: 'blur' },
    { validator: password1, trigger:'blur' }
  ],
  user_password_again: [
    { required: true, message: '两次密码不一致！', trigger: 'blur' },
    { validator: password2, trigger:'blur' }
  ]
});

const messageRules = reactive<FormRules<MessageRuleForm>>({
  customer_name: [
    { required: true, message: '姓名不能为空！', trigger: 'blur' }
  ],
  customer_sex: [
    { required: true, message: '性别不能为空！', trigger: 'blur' }
  ],
  customer_id: [
    { required: true, message: '身份证号不能为空！', trigger: 'blur' },
    { min: 18, max: 18, message: '请输入正确的身份证号！', trigger: 'blur' }
  ],
  customer_phone: [
    { required: true, message: '电话号码不能为空！', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入正确的电话号码！', trigger: 'blur' }
  ]
});

const submitForm =  (formEl: FormInstance | undefined) => {
  // 提交表单
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      if(loginDialogVisible.value) {
        login();
      }
      if(registerDialogVisible.value) {
        register();
      }
      if(messageDialogVisible.value) {
        update();
      }
    }
  });
}

function beforeunloadHandler() {
  beforeUnload_time.value = new Date().getTime();
}

function unloadHandler() {
  gap_time.value = new Date().getTime() - beforeUnload_time.value;
  if(gap_time.value <= 5) {
    exit();
  }
}

function exit() {
  if(user.user_id === null) return;
  instance.request({
    url: 'user/center/exit',
    method: 'POST',
    data: {
      user_id: user.user_id
    },
    headers: { "User-Id": user.user_id }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "退出失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          router.push('/user/index');
          user.logout();
        }
      })
      .catch(function(error){
        console.log(error);
        ElMessage({
          message: "退出失败！",
          type: "error"
        });
      });
}

function login() {
  // 登录
  if(user.user_id !== null) {
    router.push('/user/index');
  }
  instance.request({
    url: 'user/center/login',
    method: 'POST',
    data: {
      user_name: loginRuleForm.user_name,
      user_password: loginRuleForm.user_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "登录失败！",
            type: "error"
          });
        }
        if(response.data.code === "ERROR_ACCOUNT") {
          ElMessage({
            message: "账号不存在！",
            type: "error"
          });
        }
        if(response.data.code === "ERROR_PASSWORD") {
          ElMessage({
            message: "用户名或密码有误！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          user.login(response.data.data, loginRuleForm.user_name);
          ElMessage({
            message: "登录成功！",
            type: "success"
          });
          loginDialogVisible.value = false;
          registerDialogVisible.value = false;
          messageDialogVisible.value = false;

          instance.request({
            url: 'user/index/check',
            method: 'POST',
            data: {
              user_id: user.user_id
            },
            headers: { "User-Id": user.user_id }
          })
              .then(function(response) {
                if(response.data.code === "ERROR_CUSTOMER") {
                  messageDialogVisible.value = true;
                }
              })
              .catch(function(error){
                console.log(error);
                if(error.response.request.status === 401) {
                  ElMessage({
                    message: "您的连接已被注销！",
                    type: "error"
                  });
                  user.logout();
                  router.push("/user/index");
                  return;
                }
              });
        }
      })
      .catch(function(error){
        console.log(error);
        ElMessage({
          message: "登录失败！",
          type: "error"
        });
      });
}

function register() {
  // 注册
  instance.request({
    url: 'user/center/register',
    method: 'POST',
    data: {
      user_name: registerRuleForm.user_name,
      user_password: registerRuleForm.user_password
    },
    headers: { "User-Id": user.user_id }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "注册失败！",
            type: "error"
          });
        }
        if(response.data.code === "ERROR_ACCOUNT") {
          ElMessage({
            message: "用户名已被注册！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          ElMessage({
            message: "注册成功！",
            type: "success"
          });
          loginDialogVisible.value = true;
          registerDialogVisible.value = false;
          messageDialogVisible.value = false;
        }
      })
      .catch(function(error){
        console.log(error);
        ElMessage({
          message: "注册失败！",
          type: "error"
        });
      });
}

function update() {
  // 完善个人信息
  instance.request({
    url: 'user/center/usermessage/updateAll',
    method: 'POST',
    data: {
      user_id: user.user_id,
      customer_id: messageRuleForm.customer_id,
      customer_name: messageRuleForm.customer_name,
      customer_phone: messageRuleForm.customer_phone,
      customer_sex: messageRuleForm.customer_sex
    },
    headers: { "User-Id": user.user_id }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "修改失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          ElMessage({
            message: "修改成功！",
            type: "success"
          });
          loginDialogVisible.value = false;
          registerDialogVisible.value = false;
          messageDialogVisible.value = false;
        }
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "您的连接已被注销！",
            type: "error"
          });
          user.logout();
          router.push("/user/index");
          return;
        }
        ElMessage({
          message: "修改失败！",
          type: "error"
        });
      });
}

function openRegister() {
  loginDialogVisible.value = false;
  registerDialogVisible.value = true;
  messageDialogVisible.value = false;
}

function close() {
  loginDialogVisible.value = false;
  registerDialogVisible.value = false;
  messageDialogVisible.value = false;
}
</script>

<template>
  <div class="common-layout">
    <el-container class="el-container">
      <el-header height="50px">
        <user-header v-if="user.user_id !== null"/>
        <user-no-login-header v-if="user.user_id === null"/>
      </el-header>

      <el-container>
        <el-aside width="250px" class="el-aside">
          <user-aside v-if="user.user_id !== null"/>
          <user-no-login-aside v-if="user.user_id === null"/>
        </el-aside>

        <el-main>
          <main-page/>
        </el-main>

      </el-container>
    </el-container>
  </div>

  <el-dialog
      v-model="loginDialogVisible"
      :show-close="false"
      align-center
      width="25%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <el-form
        label-width="12vh"
        ref="ruleFormRef"
        :model="loginRuleForm"
        :rules="loginRules"
    >
      <el-form-item label="用户名：" prop="user_name">
        <inputter width="200" v-model="loginRuleForm.user_name"/>
      </el-form-item>

      <el-form-item label="密码：" prop="user_password">
        <password width="200" v-model="loginRuleForm.user_password"/>
      </el-form-item>


      <div class="cancel-confirm">
        <el-button color="#568fc1" plain @click="close">
          <span>取消</span>
        </el-button>
        <el-button color="#568fc1" plain @click="openRegister()">
          <span>注册</span>
        </el-button>
        <el-button color="#568fc1" class="button-color"
                   @click="submitForm(ruleFormRef)">
          <span>登录</span>
        </el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-dialog
      v-model="registerDialogVisible"
      :show-close="false"
      align-center
      width="25%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <el-form
        label-width="12vh"
        ref="ruleFormRef"
        :model="registerRuleForm"
        :rules="registerRules"
    >
      <el-form-item label="用户名：" prop="user_name">
        <inputter width="200" v-model="registerRuleForm.user_name"/>
      </el-form-item>

      <el-form-item label="密码：" prop="user_password">
        <password width="200" v-model="registerRuleForm.user_password"/>
      </el-form-item>

      <el-form-item label="确认密码：" prop="user_password_again">
        <password width="200" v-model="registerRuleForm.user_password_again"/>
      </el-form-item>

      <div class="cancel-confirm">
        <el-button color="#568fc1" plain @click="close">
          <span>取消</span>
        </el-button>
        <el-button color="#568fc1" class="button-color"
                   @click="submitForm(ruleFormRef)">
          <span>注册</span>
        </el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-dialog
      v-model="messageDialogVisible"
      :show-close="false"
      center
      align-center
      width="25%"
      title="完善个人信息"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <el-form
        label-width="12vh"
        ref="ruleFormRef"
        :model="messageRuleForm"
        :rules="messageRules"
    >
      <el-form-item label="姓名：" prop="customer_name">
        <inputter width="200" v-model="messageRuleForm.customer_name"/>
      </el-form-item>

      <el-form-item label="性别：" prop="customer_sex">
        <selector width="200" :options="customer_sex_form_options" v-model="messageRuleForm.customer_sex"/>
      </el-form-item>

      <el-form-item label="身份证号：" prop="customer_id">
        <inputter width="200" v-model="messageRuleForm.customer_id"/>
      </el-form-item>

      <el-form-item label="电话号码：" prop="customer_phone">
        <inputter width="200" v-model="messageRuleForm.customer_phone"/>
      </el-form-item>

      <div class="cancel-confirm">
        <el-button color="#568fc1" plain @click="close">
          <span>取消</span>
        </el-button>
        <el-button color="#568fc1" class="button-color"
                   @click="submitForm(ruleFormRef)">
          <span>修改</span>
        </el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<style scoped>
.el-header {
  padding: 0;
}
.el-menu {
  border: 0;
}
.el-main {
  padding: 0;
}
.el-aside {
  background-color: #2a3441;
}
.cancel-confirm {
  padding-top: 1vh;
  text-align: center;
}
.button-color {
  --el-button-hover-bg-color: rgb(238, 244, 249) !important;
  --el-button-hover-text-color: #568fc1 !important;
  --el-button-text-color: white !important;
}
</style>

